package Log;

use strict;


use English;

use File::Basename;
use FileHandle; # autoflush

my $prog;
my $log_file;



sub log_file
{
	return $log_file->{PATH} . "/" . $log_file->{NAME};
}




sub print 
{
	my ($limit_level,@message) = @_;
	print_on($log_file->{HANDLE},$limit_level,@message);
}


#-----------------------------------------------------------------------------
#print_on(file_descr, level, message)
#print_on(file_descr, level, [title], {hash_ref|table_ref}, [indent_string])
#-----------------------------------------------------------------------------
sub print_on
{
	my $dest = shift;   # file descriptor or *\STDOUT
	my $limit_level = shift;

	if ($limit_level eq "report") 
		{
		print $dest "REPORT: \n ";
		}
	elsif ($limit_level eq "format")
                {
                print $dest "REPORT:\n";
                }
	elsif ($limit_level eq "error")
		{
		print $dest "ERROR: \n";
		}
	elsif ($limit_level eq "end")
		{
		print $dest "END\n";
		}



	while (my $param = shift) 
		{
        	my $type = ref $param;
        	if (!$type) 
			{
			print $dest "$param\n\n";
			}
		 else 
			{
			my $indent = (@_) ? shift : "    ";
			if ($type eq "ARRAY") 
				{
				foreach my $elmt ( @$param )
					{
					print $dest "$indent$elmt\n";
					}
				}
			elsif ($type eq "HASH") 
				{
				foreach my $key ( sort keys %$param )
					{
					my $value = $param->{$key};
					print $dest "$indent$key => $value\n";
					}
				}
			}
		}
}




sub create_log_file
{
    
    # Name creation
        $prog = basename($PROGRAM_NAME, ".pl", ".perl"); # removes .pl and .perl ext
        my $date = `date +%Y-%m-%d_%H:%M:%S`; chomp($date);
        my $name = "${prog}_$date.log";

    
    # Opening file (and determine path)
    my $fh = new FileHandle;
    my $path = "/tmp/log";
    unless ($fh->open(">$path/$name")) {
        print STDERR "Can't open $path/$name for writing; fallback on /tmp.\n";
        $path = "/tmp";
         unless ($fh->open(">$path/$name")) {
            print STDERR "Can't open $path/$name for writing; no log file will be created.\n";
            $path = "";
            $fh->open(">/dev/null");
        }
    }
    autoflush $fh 1;
    
    my $lf = {};   # hash reference
    $lf->{NAME} = $name;
    $lf->{PATH} = $path;
    $lf->{HANDLE} = $fh;
    return $lf;
}

sub send_mail
{
my $file=shift @_;
my $f_name=basename($file);
`/data/scripts/sendmail.pl -f multisimgen.support\@tcl.com -t frederic.chailloux\@jrdcom.com -s "$f_name" $file`;
}

sub delete_log_file_if_necessary
{
return;
}


#-----------------------------------------------------------------------------
BEGIN {
    $log_file = create_log_file();
}

#-----------------------------------------------------------------------------
END {
    #delete_log_file_if_necessary($log_file);
}

1;
__END__


